package com.example.jussi.listviewdemo;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

/**
 * Created by admin on 2018/11/29.
 */

public class WeathyAdapter extends ArrayAdapter<Weathy> {

    private int resourceId;

    public WeathyAdapter(Context context, int resource, List<Weathy> objects) {
        super(context, resource, objects);
        resourceId = resource;
    }

    /*
    convertView 这个参数用于将之前加载好的布局保存
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Weathy weathy = getItem(position);   //获取当前项的 Weathy 实例
        View view;
        ViewHolder viewHolder;
        if(convertView == null){
            /*
            第一个参数：ListView子项布局的Id
            第二个参数：可以看作一个容器
            第三个参数：表示只让父布局中声明的layout属性生效
            */
            view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.weathyImage = view.findViewById(R.id.weathy_image);
            viewHolder.weathyName = view.findViewById(R.id.weathy_name);
            view.setTag(viewHolder);    //将 ViewHolder 存储在 View 中
        }else{
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }
        viewHolder.weathyImage.setImageResource(weathy.getImageId());
        viewHolder.weathyName.setText(weathy.getName());
        return view;
    }

    class ViewHolder{

        ImageView weathyImage;

        TextView weathyName;

    }
}
